import '../assets/css/index.scss';

import React, {
  useEffect,
  useState,
} from 'react';

import {
  Button,
  Card,
  Image,
  Modal,
  Space,
  Spin,
  Table,
} from 'antd';

import { WindowChannel } from '@haiyaotec/window-channel';

import {
  useAppQuery,
  useAuthenticatedFetch,
} from '../hooks';
import PhotoWall from './PhotoWall';
import { ProductVariants } from './ProductVariants';
import Search from './Search';

export const ProductsCard = () => {
  const emptyToastProps = { content: null };
  const [isLoading, setIsLoading] = useState(true);
  const [isError, setIsError] = useState(false);
  const [product, setProduct] = useState(null);
  const [image, setImage] = useState(null);

  const [open, setOpen] = useState(false);
  const [imageMap, setImageMap] = useState({});
  const [isModalVisible, setIsModalVisible] = useState(false);

  const [toastProps, setToastProps] = useState(emptyToastProps);
  const fetch = useAuthenticatedFetch();
  function aiImageAction(_product) {
    setProduct(_product)
    setImageMap(_product.images.reduce((acc, item) => {
      acc[item.id] = item.src;
      return acc;
    }, {})) 
    setOpen(true);
  }
  const handleClick = (image) => {
    setImage(image);
    showModal()
  };
  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    setIsModalVisible(false);
  };
  useEffect(() => {
    let service=WindowChannel.newChannelService(window)

    service.listen('/save_image',async (value)=>{
      try {
        const {
          data
        } = await fetch( "/api/products/update_image",{
          method:"POST",
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            attachment: value.attach.replace('data:text/json;charset=utf-8,',''),
            product_id:value.product_id,
            image_id:value.id
          })
        });
        return {code: 0}
      } catch (error) {
        console.log(error,'error')
    
        return {code: 1}
      }
      
    
    })
    // window.addEventListener('message', event => {
    //   console.log('receive message')
    //   // Check that the message is coming from the iframe and not another window
    //   if (event.origin !== 'http://localhost:3000') return;    
    //   // Log the message received from the iframe
    //   console.log('Message received from iframe:', event.data);
    // });
    
  },[])
  const handleCancel = () => {
    setIsModalVisible(false);
  };
  const columns = [
    {
      title: 'Product Name',
      dataIndex: 'title',
      key: 'title',
      render: (text, record) => (
        <>
          <span class="btn">{text}</span>
          {record.images.length > 0 ?

            <Image className='btn' src={record.image.src}  width={40}
              height={40} />
            :
            <Image className='btn'
              width={40}
              height={40}
              src="error"
              fallback=""
            />}



        </>
      ),
    },
    {
      title: 'Action',
      dataIndex: 'status',
      key: 'status',
      render: (text, record) => (
        (<Button type="primary" class="btn" onClick={() => { aiImageAction(record) }}>
          AI Imager
        </Button>
        )
      )
    },
    {
      title: 'Status',
      dataIndex: 'status',
      key: 'status',
    },
    {
      title: 'Vendor',
      dataIndex: 'vendor',
      key: 'vendor',
    },
  ];
  const {
    data
  } = useAppQuery({
    url: "/api/products",
    reactQueryOptions: {
      onSuccess: () => {
        setIsLoading(false);
      },
      onerror: () => {
        setIsError(true);
      }
    },
  });
  function get_url() {
    return `http://localhost:3000/?image_url=${image.src}&id=${image.id}&product_id=${product.key}`;
  }
  if (isLoading) return <Spin />;
  if (isError) return <p>Error :(</p>;
  return (
    <>
      <br/>
    <Search />
    <br/>
      <Table
        style={{ width: "90%" }}
        columns={columns}
        dataSource={data.data.map((node) => ({
          key: node.id,
          title: node.title,
          productType: node.product_type,
          vendor: node.vendor,
          image: node.image,
          images: node.images,
          variants: node.variants,
          status: node.status
        }))}
      />
        <Modal
        style={{
          maxWidth: "100vw",
          top: 0,
          paddingBottom: 0
        }}
        bodyStyle={{
          height: "calc(100vh - 55px - 53px)",
          overflowY: "auto"
        }}
        footer={null} 
        title="Edit Product"
        width="100vw"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        {image && <iframe src={get_url()} width={'100%'} height={'100%'} allowFullScreen></iframe>}
        
      </Modal>
      <Modal
        // title="AI Image"
        centered
        open={open}
        onOk={() => setOpen(false)}
        onCancel={() => setOpen(false)}
        width={900}
      >
        <Space direction="vertical" size={16}>
          <Card title="Media file" style={{ width: 800 }}>
          {product && 
            <PhotoWall  onClick={handleClick}  product={product} />
          }
          </Card>
          <Card size="small" title="Variants" style={{ width: 800 }}>
            {product && 
            <ProductVariants imageMap={imageMap}  variants={product.variants} />
          }
          </Card>
        </Space>
      </Modal>
    </>

  );
};
